<template>
  <div class="create-content-page">
    <div class="container">
      <div class="page-header">
        <h1>发布内容</h1>
        <p>分享你的精彩内容给更多人</p>
      </div>

      <div class="content-form-wrapper">
        <el-form
          ref="contentFormRef"
          :model="contentForm"
          :rules="contentRules"
          label-position="top"
          class="content-form"
        >
          <!-- 文件上传区域 -->
          <el-form-item label="上传文件" prop="file">
            <el-upload
              ref="uploadRef"
              class="file-uploader"
              drag
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*,video/*,.pdf,.doc,.docx,.txt"
            >
              <div v-if="!uploadedFile" class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">
                  <p class="primary-text">点击或拖拽文件到此区域上传</p>
                  <p class="secondary-text">支持图片、视频、文档等格式，最大100MB</p>
                </div>
              </div>
              
              <div v-else class="file-preview">
                <!-- 图片预览 -->
                <div v-if="isImage(uploadedFile)" class="image-preview">
                  <img :src="filePreviewUrl" alt="预览图" />
                  <div class="file-actions">
                    <el-button type="danger" size="small" @click="removeFile($event)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
                
                <!-- 视频预览 -->
                <div v-else-if="isVideo(uploadedFile)" class="video-preview">
                  <video :src="filePreviewUrl" controls></video>
                  <div class="file-actions">
                    <el-button type="danger" size="small" @click="removeFile($event)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
                
                <!-- 文档预览 -->
                <div v-else class="document-preview">
                  <div class="document-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="document-info">
                    <p class="filename">{{ uploadedFile.name }}</p>
                    <p class="filesize">{{ formatFileSize(uploadedFile.size) }}</p>
                  </div>
                  <div class="file-actions">
                    <el-button type="danger" size="small" @click="removeFile($event)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </el-upload>
          </el-form-item>

          <!-- 内容标题 -->
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="contentForm.title"
              placeholder="请输入内容标题"
              size="large"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <!-- 内容描述 -->
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="contentForm.description"
              type="textarea"
              placeholder="请输入内容描述"
              :rows="4"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <!-- 内容标签 -->
          <el-form-item label="标签">
            <div class="tags-input">
              <el-tag
                v-for="(tag, index) in contentForm.tags"
                :key="index"
                closable
                @close="removeTag(index)"
                class="content-tag"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="tagInputRef"
                v-model="inputValue"
                size="small"
                class="tag-input"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button
                v-else
                size="small"
                @click="showInput"
                class="add-tag-btn"
              >
                + 添加标签
              </el-button>
            </div>
          </el-form-item>

          <!-- 内容类型 -->
          <el-form-item label="内容类型" prop="type">
            <el-radio-group v-model="contentForm.type">
              <el-radio label="IMAGE">图片</el-radio>
              <el-radio label="VIDEO">视频</el-radio>
              <el-radio label="DOCUMENT">文档</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 发布设置 -->
          <el-form-item label="发布设置">
            <el-switch
              v-model="contentForm.published"
              active-text="立即发布"
              inactive-text="保存草稿"
            />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <div class="form-actions">
              <el-button size="large" @click="$router.go(-1)">
                取消
              </el-button>
              <el-button
                type="primary"
                size="large"
                :loading="submitting"
                @click="handleSubmit"
              >
                {{ submitting ? '发布中...' : (contentForm.published ? '发布内容' : '保存草稿') }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Document } from '@element-plus/icons-vue'
import { createContent } from '@/api/content'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()

// 响应式数据
const contentFormRef = ref()
const uploadRef = ref()
const tagInputRef = ref()
const submitting = ref(false)
const uploadedFile = ref(null)
const filePreviewUrl = ref('')
const inputVisible = ref(false)
const inputValue = ref('')

// 表单数据
const contentForm = reactive({
  title: '',
  description: '',
  tags: [],
  type: 'IMAGE',
  published: true,
  file: null
})

// 表单验证规则
const contentRules = {
  title: [
    { required: true, message: '请输入内容标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度为2-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入内容描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度为10-500个字符', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请上传文件', trigger: 'change' }
  ]
}

// 文件上传处理
const handleFileChange = (file) => {
  console.log('🔍 文件选择:', file)
  console.log('🔍 原始文件:', file.raw)
  
  // 获取原始文件对象
  const rawFile = file.raw || file
  
  // 检查文件大小 (100MB = 100 * 1024 * 1024 字节)
  const maxSize = 100 * 1024 * 1024
  const fileSize = rawFile.size || file.size
  
  if (fileSize > maxSize) {
    ElMessage.error(`文件大小不能超过 100MB，当前文件大小: ${(fileSize / 1024 / 1024).toFixed(2)}MB`)
    return false
  }
  
  // 检查文件类型 - 使用原始文件的type
  const fileType = rawFile.type || file.type
  console.log('🔍 文件类型:', fileType)
  
  const allowedTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv', 'video/webm', 
                       'image/jpeg', 'image/png', 'image/gif', 'image/webp',
                       'audio/mp3', 'audio/wav', 'audio/aac', 'audio/ogg']
  
  if (!allowedTypes.includes(fileType)) {
    ElMessage.error(`不支持的文件类型: ${fileType}，请上传视频、图片或音频文件`)
    return false
  }
  
  // 保存原始文件对象
  contentForm.file = rawFile
  uploadedFile.value = file // 保存包装对象用于UI显示
  
  // 根据文件类型设置内容类型
  if (fileType.startsWith('video/')) {
    contentForm.type = 'VIDEO'
  } else if (fileType.startsWith('image/')) {
    contentForm.type = 'IMAGE'
  } else if (fileType.startsWith('audio/')) {
    contentForm.type = 'AUDIO'
  }
  
  // 生成预览URL
  if (rawFile) {
    filePreviewUrl.value = URL.createObjectURL(rawFile)
  }
  
  ElMessage.success(`文件上传成功: ${rawFile.name || file.name}`)
  return false // 阻止自动上传
}

const removeFile = (event) => {
  // 阻止事件冒泡，避免触发upload组件的点击事件
  if (event) {
    event.stopPropagation()
    event.preventDefault()
  }
  
  uploadedFile.value = null
  contentForm.file = null
  
  if (filePreviewUrl.value) {
    URL.revokeObjectURL(filePreviewUrl.value)
    filePreviewUrl.value = ''
  }
  
  // 清除upload组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 文件类型判断
const isImage = (file) => {
  if (!file) return false
  const rawFile = file.raw || file
  return rawFile.type && rawFile.type.startsWith('image/')
}

const isVideo = (file) => {
  if (!file) return false
  const rawFile = file.raw || file
  return rawFile.type && rawFile.type.startsWith('video/')
}

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 标签处理方法
const removeTag = (index) => {
  contentForm.tags.splice(index, 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !contentForm.tags.includes(inputValue.value)) {
    if (contentForm.tags.length < 5) {
      contentForm.tags.push(inputValue.value)
    } else {
      ElMessage.warning('最多添加5个标签')
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 重置表单
const resetForm = () => {
  contentForm.title = ''
  contentForm.description = ''
  contentForm.tags = []
  contentForm.type = 'VIDEO'
  contentForm.published = true
  contentForm.file = null
  
  if (contentFormRef.value) {
    contentFormRef.value.resetFields()
  }
  
  console.log('🔄 表单已重置')
}

// 提交处理
const handleSubmit = async () => {
  if (!contentFormRef.value) return
  
  // 检查token状态
  const authStore = useAuthStore()
  console.log('当前token:', authStore.token)
  console.log('登录状态:', authStore.isLoggedIn)
  
  if (!authStore.token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  try {
    const valid = await contentFormRef.value.validate()
    if (!valid) {
      console.log('表单验证失败')
      return
    }
    
    if (!contentForm.file) {
      ElMessage.error('请先上传文件')
      return
    }
    
    submitting.value = true
    
    // 显示上传进度提示
    ElMessage.info('正在上传文件，请稍候...')
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', contentForm.file)
    
    // 创建内容请求对象
    const contentRequest = {
      title: contentForm.title,
      description: contentForm.description,
      tags: contentForm.tags.join(','),
      type: contentForm.type,
      published: contentForm.published
    }
    
    console.log('发送的内容请求:', contentRequest)
    
    // 将content对象作为JSON Blob添加到FormData，设置正确的Content-Type
    const contentBlob = new Blob([JSON.stringify(contentRequest)], {
      type: 'application/json'
    })
    formData.append('content', contentBlob)
    
    const response = await createContent(formData)
    
    if (response.success) {
      ElMessage.success('内容发布成功！')
      console.log('✅ 内容创建成功:', response.data)
      
      // 重置表单
      resetForm()
      
      // 跳转到内容详情页或首页
      router.push('/')
    } else {
      ElMessage.error(response.message || '发布失败')
      console.log('❌ 发布失败:', response.message)
    }
  } catch (error) {
    console.error('❌ 发布失败:', error)
    console.log('❌ 错误详情:', error.response?.data)
    
    // 根据错误类型显示不同的提示
    if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络连接失败，请检查网络连接后重试')
    } else if (error.response?.status === 413) {
      ElMessage.error('文件太大，请选择小于100MB的文件')
    } else if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      authStore.logout()
    } else if (error.response?.status === 400) {
      const errorMessage = error.response?.data?.message || '请求参数错误'
      ElMessage.error(errorMessage)
    } else {
      const errorMessage = error.response?.data?.message || error.message || '发布失败，请稍后重试'
      ElMessage.error(errorMessage)
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped lang="scss">
@import "@/styles/variables.scss";

.create-content-page {
  min-height: 100vh;
  background: $bg-light;
  padding: $spacing-xl 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 $spacing-lg;
}

.page-header {
  text-align: center;
  margin-bottom: $spacing-xxl;
  
  h1 {
    color: $text-primary;
    font-size: $font-size-xxl;
    margin-bottom: $spacing-sm;
  }
  
  p {
    color: $text-secondary;
    font-size: $font-size-md;
  }
}

.content-form-wrapper {
  background: $bg-white;
  border-radius: $border-radius-large;
  padding: $spacing-xxl;
  box-shadow: $shadow-light;
}

.content-form {
  .file-uploader {
    width: 100%;
    
    :deep(.el-upload) {
      width: 100%;
      border: 2px dashed $border-color;
      border-radius: $border-radius-medium;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: $primary-color;
      }
    }
    
    :deep(.el-upload-dragger) {
      width: 100%;
      height: 200px;
      background: $bg-white;
      border: none;
      border-radius: $border-radius-medium;
    }
  }
  
  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    
    .upload-icon {
      font-size: $font-size-xxl * 2;
      color: $text-placeholder;
      margin-bottom: $spacing-md;
    }
    
    .upload-text {
      text-align: center;
      
      .primary-text {
        font-size: $font-size-md;
        color: $text-secondary;
        margin-bottom: $spacing-xs;
      }
      
      .secondary-text {
        font-size: $font-size-sm;
        color: $text-placeholder;
      }
    }
  }
  
  .file-preview {
    position: relative;
    width: 100%;
    height: 200px;
    border-radius: $border-radius-medium;
    overflow: hidden;
    
    .image-preview,
    .video-preview {
      width: 100%;
      height: 100%;
      position: relative;
      
      img,
      video {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .document-preview {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      background: $bg-light;
      gap: $spacing-md;
      
      .document-icon {
        font-size: $font-size-xxl * 2;
        color: $primary-color;
      }
      
      .document-info {
        .filename {
          font-size: $font-size-md;
          color: $text-primary;
          margin-bottom: $spacing-xs;
        }
        
        .filesize {
          font-size: $font-size-sm;
          color: $text-secondary;
        }
      }
    }
    
    .file-actions {
      position: absolute;
      top: $spacing-sm;
      right: $spacing-sm;
    }
  }
  
  .tags-input {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-sm;
    align-items: center;
    
    .content-tag {
      background: $primary-light;
      color: $primary-color;
      border: 1px solid $primary-color;
    }
    
    .tag-input {
      width: 120px;
    }
    
    .add-tag-btn {
      border: 1px dashed $border-color;
      color: $text-secondary;
      
      &:hover {
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }
  
  .form-actions {
    display: flex;
    justify-content: center;
    gap: $spacing-md;
    margin-top: $spacing-xl;
  }
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .container {
    padding: 0 $spacing-md;
  }
  
  .content-form-wrapper {
    padding: $spacing-xl;
  }
  
  .file-preview {
    height: 150px;
  }
}

@media (max-width: $breakpoint-sm) {
  .content-form-wrapper {
    padding: $spacing-lg;
  }
  
  .form-actions {
    flex-direction: column;
    
    .el-button {
      width: 100%;
    }
  }
}
</style> 